package me.zhengjie.pay.rest;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.service.partnerpayments.jsapi.JsapiService;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.QueryOrderByIdRequest;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.QueryOrderByOutTradeNoRequest;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.QueryByOutRefundNoRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.rest.AnonymousGetMapping;
import me.zhengjie.business.service.GsglService;
import me.zhengjie.config.WechatPayConfig;
import me.zhengjie.modules.system.domain.vo.GsglScale;
import me.zhengjie.modules.system.repository.GsglScaleRepository;
import me.zhengjie.pay.domain.JjzhWxPayOrders;
import me.zhengjie.pay.service.JjzhWxPayOrdersService;
import me.zhengjie.pay.task.DownloadTradebillTask;
import me.zhengjie.utils.PageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
@RequestMapping("/api/wechat")
public class WechatController {
    @Autowired
    private JjzhWxPayOrdersService jjzhWxPayOrdersService;
    private static final Logger logger = LoggerFactory.getLogger(WxRefundController.class);

    @Autowired
    private DownloadTradebillTask downloadTradebillTask;
    @Autowired
    private GsglService gsglService;

    @Autowired
    private WechatPayConfig wechatPayConfig;

    @Autowired
    private GsglScaleRepository gsglScaleRepository;


    @GetMapping(value = "/wechat")
    @AnonymousGetMapping
    @ResponseBody
    public void auth6(HttpServletRequest request,
                      HttpServletResponse response) {
        logger.info("auth checking start...");
        try {
            String nonce = request.getParameter("nonce");
            String timestamp = request.getParameter("timestamp");
            String signature = request.getParameter("signature");
            String echoStr = request.getParameter("echostr");
            logger.info("auth,nonce:{},timestamp:{},signature:{},echoStr:{}", nonce, timestamp, signature, echoStr);
            response.setContentType("text/html");
            response.getWriter().print(echoStr);
            logger.info("auth echoStr:" + echoStr);
            logger.info("auth checking success!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping(value = "/amount")
    @ResponseBody
    public ResponseEntity<Object> getAmount(String bisZhsqHldzSsqx) {

        GsglScale gsglScale = gsglScaleRepository.findByDeptId(bisZhsqHldzSsqx);
        String sbgsId = gsglScale.getGsglId();

        String isPay = gsglService.findByBisGsglId(sbgsId).getIsPay();

        HashMap<String, Object> map = new HashMap<>();
        map.put("isPay","1".equals(isPay) ? true : false);
        map.put("amount",wechatPayConfig.getAmount()/100);
        return new ResponseEntity<>(PageUtil.toMpContent(map), HttpStatus.OK);
    }



    /**
     * 根据微信支付订单号查询订单
     * @param request
     * @return
     */
    @GetMapping("/query")
    public ResponseEntity<Object> queryOrderById(HttpServletRequest request) {
        String orderNo = request.getParameter("orderNo");
        String mchId = wechatPayConfig.getMchId();
        Config config = wechatPayConfig.getNotificationConfig();
        logger.info("开始处理查询订单接口，订单号：{}", orderNo);
        // 查询订单
        JjzhWxPayOrders order = jjzhWxPayOrdersService.findByOrderNo(orderNo);
        if (order == null) {
            logger.error("查询失败：订单不存在，订单号：{}", orderNo);
            throw new RuntimeException("订单不存在");
        }
        QueryOrderByIdRequest queryRequest = new QueryOrderByIdRequest();
        queryRequest.setSpMchid(mchId);
        queryRequest.setSubMchid(order.getSubMchind());
        queryRequest.setTransactionId(order.getTransactionId());

        JsapiService service = new JsapiService.Builder().config(config).build();
        Transaction result = service.queryOrderById(queryRequest);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 根据商户订单号查询订单
     * @param request
     * @return
     */
    @GetMapping("/queryByOutTradeNo")
    public ResponseEntity<Object> queryOrderByOutTradeNo(HttpServletRequest request) {
        String orderNo = request.getParameter("orderNo");
        String mchId = wechatPayConfig.getMchId();
        Config config = wechatPayConfig.getNotificationConfig();
        logger.info("开始处理查询订单接口，订单号：{}", orderNo);
        // 查询订单
        JjzhWxPayOrders order = jjzhWxPayOrdersService.findByOrderNo(orderNo);
        if (order == null) {
            logger.error("查询失败：订单不存在，订单号：{}", orderNo);
            throw new RuntimeException("订单不存在");
        }
        QueryOrderByOutTradeNoRequest queryOrderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest();
        queryOrderByOutTradeNoRequest.setOutTradeNo(orderNo);
        queryOrderByOutTradeNoRequest.setSpMchid(mchId);
        queryOrderByOutTradeNoRequest.setSubMchid(order.getSubMchind());
        JsapiService service = new JsapiService.Builder().config(config).build();
        Transaction result = service.queryOrderByOutTradeNo(queryOrderByOutTradeNoRequest);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }



    // 查询单笔退款（按商户退款单号）
    @GetMapping("/queryRefund")
    public ResponseEntity<Object> queryRefund(HttpServletRequest request) {
        String refundNo = request.getParameter("orderNo");  // 商户退款单号
        Config config = wechatPayConfig.getNotificationConfig();
        logger.info("开始处理退款查询请求，商户退款单号：{}", refundNo);

        // 查询订单
        JjzhWxPayOrders order = jjzhWxPayOrdersService.findByOrderNo(refundNo);
        // 查询退款
        if (order == null) {
            logger.error("查询失败：订单不存在，订单号：{}", refundNo);
            throw new RuntimeException("订单不存在");
        }

        // 构造退款查询请求
        // 使用微信支付 SDK 查询退款
        RefundService refundService = new RefundService.Builder().config(config).build();
        QueryByOutRefundNoRequest queryByOutRefundNoRequest = new QueryByOutRefundNoRequest();
        queryByOutRefundNoRequest.setOutRefundNo(order.getOutRefundNo());
        queryByOutRefundNoRequest.setSubMchid(order.getSubMchind());

        Refund refund = refundService.queryByOutRefundNo(queryByOutRefundNoRequest);

        logger.info("退款查询成功，商户退款单号：{}", refundNo);
        return new ResponseEntity<>(refund, HttpStatus.OK);
    }


    @GetMapping("/download")
    @AnonymousAccess
    public String download(String subMchid) throws Exception {
        downloadTradebillTask.downloadTradeBill();
        return "ok";
    }

}
